//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Mail;
using System.Net.Mime;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using System.Xml;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Users;
using DotNetNuke.Security;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.Log.EventLog;
using DotNetNuke.Services.Mail;
using DotNetNuke.Services.Personalization;
namespace DotNetNuke.Modules.Admin.LogViewer
{
	partial class LogViewer : DotNetNuke.Entities.Modules.PortalModuleBase, Entities.Modules.IActionable
	{
		ArrayList arrLogTypeInfo;
		Hashtable htLogTypeInfo;
		bool ColorCodingOn = false;
		bool ColorCodingLegendOn = true;
		int PageIndex = 1;
		int intPortalID = -1;
		string strLogTypeKey;
		private void BindData()
		{
			btnEmail.Attributes.Add("onclick", "return CheckExceptions();");
			if (UserInfo.IsSuperUser)
			{
				if (!Page.IsPostBack && Request.QueryString["pid"] != null)
				{
					ddlPortalid.Items.FindByValue(Request.QueryString["pid"]).Selected = true;
				}
				intPortalID = Int32.Parse(ddlPortalid.SelectedItem.Value);
			}
			else
			{
				intPortalID = PortalId;
			}
			int TotalRecords = 0;
			int PageSize = Convert.ToInt32(ddlRecordsPerPage.SelectedValue);
			if (!Page.IsPostBack && Request.QueryString["LogTypeKey"] != null)
			{
				ListItem li = ddlLogType.Items.FindByValue(Request.QueryString["LogTypeKey"]);
				if (li != null)
				{
					li.Selected = true;
				}
			}
			strLogTypeKey = ddlLogType.SelectedItem.Value;
			LogInfoArray objLog;
			int CurrentPage = PageIndex;
			if (CurrentPage > 0)
				CurrentPage = CurrentPage - 1;
			LogController objLogController = new LogController();
			if (intPortalID == -1 && strLogTypeKey == "*")
			{
				objLog = objLogController.GetLog(PageSize, CurrentPage, ref TotalRecords);
			}
			else if (intPortalID == -1 && strLogTypeKey != "*")
			{
				objLog = objLogController.GetLog(strLogTypeKey, PageSize, CurrentPage, ref TotalRecords);
			}
			else if (intPortalID != -1 && strLogTypeKey == "*")
			{
				objLog = objLogController.GetLog(intPortalID, PageSize, CurrentPage, ref TotalRecords);
			}
			else if (intPortalID != -1 && strLogTypeKey != "*")
			{
				objLog = objLogController.GetLog(intPortalID, strLogTypeKey, PageSize, CurrentPage, ref TotalRecords);
			}
			else
			{
				objLog = objLogController.GetLog(strLogTypeKey, PageSize, CurrentPage, ref TotalRecords);
			}
			if (objLog.Count > 0)
			{
				dlLog.Visible = true;
				pnlSendExceptions.Visible = this.IsEditable;
				if (ColorCodingOn)
				{
					chkColorCoding.Checked = true;
				}
				else
				{
					chkColorCoding.Checked = false;
				}
				if (ColorCodingLegendOn)
				{
					pnlLegend.Visible = true;
				}
				else
				{
					pnlLegend.Visible = false;
				}
				if (UserInfo.IsSuperUser)
				{
					btnDelete.Visible = true;
					btnClear.Visible = true;
				}
				else
				{
					btnDelete.Visible = false;
					btnClear.Visible = false;
				}
				pnlOptions.Visible = true;
				tblInstructions.Visible = true;
				dlLog.DataSource = objLog;
				dlLog.DataBind();
				InitializePaging(ctlPagingControlBottom, TotalRecords, PageSize);
			}
			else
			{
				UI.Skins.Skin.AddModuleMessage(this, Services.Localization.Localization.GetString("NoEntries", this.LocalResourceFile), UI.Skins.Controls.ModuleMessage.ModuleMessageType.YellowWarning);
				dlLog.Visible = false;
				pnlSendExceptions.Visible = false;
				btnDelete.Visible = false;
				btnClear.Visible = false;
				pnlLegend.Visible = false;
				tblInstructions.Visible = false;
				ctlPagingControlBottom.Visible = false;
				chkColorCoding.Checked = false;
			}
		}
		private void InitializePaging(DotNetNuke.UI.WebControls.PagingControl ctlPagingControl, int TotalRecords, int PageSize)
		{
			ctlPagingControl.TotalRecords = TotalRecords;
			ctlPagingControl.PageSize = PageSize;
			ctlPagingControl.CurrentPage = PageIndex;
			string strQuerystring = "";
			if (ddlRecordsPerPage.SelectedIndex != 0)
			{
				strQuerystring += "&PageRecords=" + ddlRecordsPerPage.SelectedValue;
			}
			if (intPortalID >= 0)
			{
				strQuerystring += "&pid=" + intPortalID.ToString();
			}
			if (strLogTypeKey != "*" && !String.IsNullOrEmpty(strLogTypeKey))
			{
				strQuerystring += "&LogTypeKey=" + strLogTypeKey;
			}
			ctlPagingControl.QuerystringParams = strQuerystring;
			ctlPagingControl.TabID = TabId;
		}
		private void BindLogTypeDropDown()
		{
			LogController objLogController = new LogController();
			ArrayList arrLogTypes = new ArrayList();
			arrLogTypes = objLogController.GetLogTypeInfo();
			arrLogTypes.Sort(new LogTypeSortFriendlyName());
			ddlLogType.DataTextField = "LogTypeFriendlyName";
			ddlLogType.DataValueField = "LogTypeKey";
			ddlLogType.DataSource = arrLogTypes;
			ddlLogType.DataBind();
			ListItem ddlAllPortals = new ListItem(Services.Localization.Localization.GetString("All"), "*");
			ddlLogType.Items.Insert(0, ddlAllPortals);
		}
		private void BindPortalDropDown()
		{
			PortalSecurity objPortalSecurity = new PortalSecurity();
			int i;
			if (UserInfo.IsSuperUser)
			{
				PortalController objPortalController = new PortalController();
				ArrayList arrPortals = new ArrayList();
				arrPortals = objPortalController.GetPortals();
				arrPortals.Sort(new PortalSortTitle());
				ddlPortalid.DataTextField = "PortalName";
				ddlPortalid.DataValueField = "PortalID";
				ddlPortalid.DataSource = arrPortals;
				ddlPortalid.DataBind();
				ListItem ddlAllPortals = new ListItem(Services.Localization.Localization.GetString("All"), "-1");
				ddlPortalid.Items.Insert(0, ddlAllPortals);
				for (i = 0; i <= ddlPortalid.Items.Count - 1; i++)
				{
					if (String.IsNullOrEmpty(ddlPortalid.Items[i].Text))
					{
						ddlPortalid.Items[i].Text = "Portal: " + ddlPortalid.Items[i].Value;
					}
				}
			}
			else
			{
				plPortalID.Visible = false;
				ddlPortalid.Visible = false;
			}
		}
		private void DeleteSelectedExceptions()
		{
			try
			{
				System.Text.StringBuilder strXMLOut = new System.Text.StringBuilder();
				string s = Request.Form["Exception"];
				if (s != null)
				{
					string[] arrExcPositions = null;
					if (s.LastIndexOf(",") > 0)
					{
						arrExcPositions = s.Split(Convert.ToChar(","));
					}
					else if (!String.IsNullOrEmpty(s))
					{
						arrExcPositions = new string[] { s };
					}
					LogController objLoggingController = new LogController();
					int j = arrExcPositions.Length;
					for (int i = 0; i < arrExcPositions.Length; i++)
					{
						j -= 1;
						string[] excKey;
						excKey = arrExcPositions[j].Split(Convert.ToChar("|"));
						LogInfo objLogInfo = new LogInfo();
						objLogInfo.LogGUID = excKey[0];
						objLogInfo.LogFileID = excKey[1];
						objLoggingController.DeleteLog(objLogInfo);
					}
					UI.Skins.Skin.AddModuleMessage(this, Services.Localization.Localization.GetString("DeleteSuccess", this.LocalResourceFile), UI.Skins.Controls.ModuleMessage.ModuleMessageType.GreenSuccess);
				}
				BindPortalDropDown();
				BindData();
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private XmlDocument GetSelectedExceptions()
		{
			XmlDocument objXML = new XmlDocument();
			try
			{
				System.Text.StringBuilder strXMLOut = new System.Text.StringBuilder();
				string s = Request.Form["Exception"];
				if (s != null)
				{
					string[] arrExcPositions = null;
					if (s.LastIndexOf(",") > 0)
					{
						arrExcPositions = s.Split(Convert.ToChar(","));
					}
					else if (!String.IsNullOrEmpty(s))
					{

						arrExcPositions = new string[] { s };
					}
					LogController objLoggingController = new LogController();
					objXML.LoadXml("<LogEntries></LogEntries>");
					int j = arrExcPositions.Length;
					for (int i = 0; i < arrExcPositions.Length; i++)
					{
						j -= 1;
						string[] excKey;
						excKey = arrExcPositions[j].Split(Convert.ToChar("|"));
						LogInfo objLogInfo = new LogInfo();
						objLogInfo.LogGUID = excKey[0];
						objLogInfo.LogFileID = excKey[1];
						XmlNode objNode;
						objNode = objXML.ImportNode((XmlNode)objLoggingController.GetSingleLog(objLogInfo, LoggingProvider.ReturnType.XML), true);
						objXML.DocumentElement.AppendChild(objNode);
					}
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
			return objXML;
		}
		private void SendEmail()
		{
			string strEmail = GetSelectedExceptions().OuterXml;
			string strFromEmailAddress;
			UserController _userController = new UserController();
			if (!String.IsNullOrEmpty(UserInfo.Email))
			{
				strFromEmailAddress = UserInfo.Email;
			}
			else
			{
				strFromEmailAddress = PortalSettings.Email;
			}
			if (string.IsNullOrEmpty(txtSubject.Text))
			{
				txtSubject.Text = PortalSettings.PortalName + " Exceptions";
			}
			string ReturnMsg;
			if (Regex.IsMatch(strFromEmailAddress, Common.Globals.glbEmailRegEx))
			{
				string fileName = "errorlog.xml";
				string filePath = PortalSettings.HomeDirectoryMapPath + fileName;
				XmlDocument xmlDoc = GetSelectedExceptions();
				xmlDoc.Save(filePath);
				List<Attachment> attachments = new List<Attachment>();
				ContentType ct = new ContentType();
				ct.MediaType = MediaTypeNames.Text.Xml;
				ct.Name = fileName;
				Attachment attachment = new Attachment(filePath, ct);
				attachments.Add(attachment);
			    ReturnMsg = Mail.SendEmail(strFromEmailAddress, strFromEmailAddress, txtEmailAddress.Text, txtSubject.Text,
			                               txtMessage.Text, attachments);
				FileSystemUtils.DeleteFile(filePath);
				if (String.IsNullOrEmpty(ReturnMsg))
				{
					UI.Skins.Skin.AddModuleMessage(this, Services.Localization.Localization.GetString("EmailSuccess", this.LocalResourceFile), UI.Skins.Controls.ModuleMessage.ModuleMessageType.GreenSuccess);
				}
				else
				{
					UI.Skins.Skin.AddModuleMessage(this, Services.Localization.Localization.GetString("EmailFailure", this.LocalResourceFile) + " " + ReturnMsg, UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
				}
			}
			else
			{
				ReturnMsg = string.Format(Localization.GetString("InavlidEmailAddress", this.LocalResourceFile), strFromEmailAddress);
				UI.Skins.Skin.AddModuleMessage(this, Services.Localization.Localization.GetString("EmailFailure", this.LocalResourceFile) + " " + ReturnMsg, UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
			}
			BindData();
		}
		protected LogTypeInfo GetMyLogType(string LogTypeKey)
		{
			LogTypeInfo objLogTypeInfo;
			if (htLogTypeInfo[LogTypeKey] != null)
			{
				objLogTypeInfo = (LogTypeInfo)htLogTypeInfo[LogTypeKey];
				if (!ColorCodingOn)
				{
					objLogTypeInfo.LogTypeCSSClass = "Normal";
				}
				return objLogTypeInfo;
			}
			else
			{
				return new LogTypeInfo();
			}
		}
		public string GetPropertiesText(object obj)
		{
			LogInfo objLogInfo = (LogInfo)obj;
			LogProperties objLogProperties = objLogInfo.LogProperties;
			System.Text.StringBuilder str = new System.Text.StringBuilder();
			int i;
			for (i = 0; i <= objLogProperties.Count - 1; i++)
			{
				LogDetailInfo ldi = (LogDetailInfo)objLogProperties[i];
				str.Append("<b>" + ldi.PropertyName + "</b>: " + Server.HtmlEncode(ldi.PropertyValue) + "<br>");
			}
			str.Append(Services.Localization.Localization.GetString("ServerName", this.LocalResourceFile) + Server.HtmlEncode(objLogInfo.LogServerName) + "<br>");
			return str.ToString();
		}
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			if (Request.QueryString["CurrentPage"] != null)
			{
				PageIndex = Convert.ToInt32(Request.QueryString["CurrentPage"]);
			}
			LogController l = new LogController();
			arrLogTypeInfo = l.GetLogTypeInfo();
			htLogTypeInfo = new Hashtable();
			int i;
			for (i = 0; i <= arrLogTypeInfo.Count - 1; i++)
			{
				LogTypeInfo objLogTypeInfo = (LogTypeInfo)arrLogTypeInfo[i];
				htLogTypeInfo.Add(objLogTypeInfo.LogTypeKey, objLogTypeInfo);
			}
			string ColorCoding;
			ColorCoding = Convert.ToString(Personalization.GetProfile("LogViewer", "ColorCoding"));
			if (ColorCoding == "0")
			{
				ColorCodingOn = false;
			}
			else if (ColorCoding == "1")
			{
				ColorCodingOn = true;
			}
			else
			{
				ColorCodingOn = true;
			}
			string ColorCodingLegend;
			ColorCodingLegend = Convert.ToString(Personalization.GetProfile("LogViewer", "ColorCodingLegend"));
			if (ColorCodingLegend == "0")
			{
				ColorCodingLegendOn = false;
			}
			else if (ColorCodingLegend == "1")
			{
				ColorCodingLegendOn = true;
			}
			else
			{
				ColorCodingLegendOn = true;
			}
		}
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			btnClear.Click += new EventHandler(btnClear_Click);
			btnDelete.Click += new EventHandler(btnDelete_Click);
			btnEmail.Click += new EventHandler(btnEmail_Click);
			chkColorCoding.CheckedChanged += new EventHandler(chkColorCoding_CheckedChanged);
			ddlLogType.SelectedIndexChanged += new EventHandler(ddlLogType_SelectedIndexChanged);
			ddlPortalid.SelectedIndexChanged += new EventHandler(ddlPortalID_SelectedIndexChanged);
			ddlRecordsPerPage.SelectedIndexChanged += new EventHandler(ddlRecordsPerPage_SelectedIndexChanged);

			try
			{
				PortalSecurity objPortalSecurity = new PortalSecurity();
				if (Page.IsPostBack == false)
				{
					LogController objLC = new LogController();
					objLC.PurgeLogBuffer();
					if (Request.QueryString["PageRecords"] != null)
					{
						ddlRecordsPerPage.SelectedValue = Request.QueryString["PageRecords"];
					}
					BindPortalDropDown();
					BindLogTypeDropDown();
					BindData();
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void btnClear_Click(System.Object sender, System.EventArgs e)
		{
			LogController objLoggingController = new LogController();
			objLoggingController.ClearLog();
			UI.Skins.Skin.AddModuleMessage(this, Services.Localization.Localization.GetString("LogCleared", this.LocalResourceFile), UI.Skins.Controls.ModuleMessage.ModuleMessageType.GreenSuccess);
			Services.Log.EventLog.EventLogController objEventLog = new Services.Log.EventLog.EventLogController();
			objEventLog.AddLog(Services.Localization.Localization.GetString("LogCleared", this.LocalResourceFile), Services.Localization.Localization.GetString("Username", this.LocalResourceFile) + ":" + UserInfo.Username, PortalSettings, -1, DotNetNuke.Services.Log.EventLog.EventLogController.EventLogType.ADMIN_ALERT);
			BindPortalDropDown();
			dlLog.Visible = false;
			pnlSendExceptions.Visible = false;
			btnDelete.Visible = false;
			btnClear.Visible = false;
			pnlOptions.Visible = false;
			pnlLegend.Visible = false;
			tblInstructions.Visible = false;
			ctlPagingControlBottom.Visible = false;
		}
		private void btnDelete_Click(System.Object sender, System.EventArgs e)
		{
			DeleteSelectedExceptions();
		}
		private void btnEmail_Click(System.Object sender, System.EventArgs e)
		{
			switch (optEmailType.SelectedValue)
			{
				case "Email":
					SendEmail();
					break;
			}
		}
		private void chkColorCoding_CheckedChanged(System.Object sender, System.EventArgs e)
		{
			int i;
			if (chkColorCoding.Checked)
			{
				i = 1;
				ColorCodingOn = true;
				ColorCodingLegendOn = true;
				Personalization.SetProfile("LogViewer", "ColorCodingLegend", "1");
			}
			else
			{
				i = 0;
				ColorCodingOn = false;
				ColorCodingLegendOn = false;
			}
			Personalization.SetProfile("LogViewer", "ColorCoding", i);
			BindData();
		}
		private void ddlLogType_SelectedIndexChanged(System.Object sender, System.EventArgs e)
		{
			PageIndex = 1;
			BindData();
		}
		private void ddlPortalID_SelectedIndexChanged(System.Object sender, System.EventArgs e)
		{
			PageIndex = 1;
			BindData();
		}
		private void ddlRecordsPerPage_SelectedIndexChanged(System.Object sender, System.EventArgs e)
		{
			PageIndex = 1;
			BindData();
		}
		public ModuleActionCollection ModuleActions
		{
			get
			{
				ModuleActionCollection Actions = new ModuleActionCollection();
				if (IsEditable)
				{
					Actions.Add(GetNextActionID(), Services.Localization.Localization.GetString(ModuleActionType.AddContent, LocalResourceFile), ModuleActionType.AddContent, "", "", EditUrl(), false, SecurityAccessLevel.Host, true, false);
				}
				return Actions;
			}
		}
	}
}
